package com.mojiayi.learn.sentinel.dubbo.system.aop;

import com.mojiayi.learn.common.enums.ResponseStatusEnum;
import com.mojiayi.learn.common.result.BaseResultSet;
import com.mojiayi.learn.common.result.ListResultSet;
import com.mojiayi.learn.common.result.PageResultSet;
import com.mojiayi.learn.common.result.ResultSet;
import org.aspectj.lang.ProceedingJoinPoint;
import org.aspectj.lang.Signature;
import org.aspectj.lang.annotation.Around;
import org.aspectj.lang.annotation.Aspect;
import org.aspectj.lang.reflect.MethodSignature;
import org.springframework.stereotype.Component;

/**
 * 异常处理切面类.
 *
 */
@Aspect
@Component
public class ExceptionAspect {

    /**
     * 异常处理切面方法.
     * 
     * @param joinPoint 接入点
     * @return Object
     * @throws Throwable 异常
     */
    @Around("execution(* com.mojiayi.learn.sentinel.dubbo.provider..*.*(..))")
    public Object exceptionAspect(ProceedingJoinPoint joinPoint) throws Throwable {
        BaseResultSet<?> resultSet = new BaseResultSet<>();
        Signature signature = joinPoint.getSignature();
        Class returnType = ((MethodSignature) signature).getReturnType();
        if (returnType.isAssignableFrom(PageResultSet.class)) {
            resultSet = new PageResultSet<>();
        } else if (returnType.isAssignableFrom(ListResultSet.class)) {
            resultSet = new ListResultSet<>();
        } else if (returnType.isAssignableFrom(ResultSet.class)) {
            resultSet = new ResultSet<>();
        }
        Object[] args = joinPoint.getArgs();
        try {
            return joinPoint.proceed(args);
        } catch (Exception e) {
            resultSet.updateFailure(ResponseStatusEnum.SERVER_BUSY.getMsg(), e.getMessage());
        }
        return resultSet;
    }

}
